package com.sjc.consumer.controller;

import com.sjc.consumer.dao.TransferDao;
import com.sjc.consumer.service.ITransferService;
import com.sjc.feign.service.IAccountService;
import org.bytesoft.compensable.Compensable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@Compensable(interfaceClass = ITransferService.class,
        confirmableKey = "transferServiceConfirm",
        cancellableKey = "transferServiceCancel")
@RestController
public class TransferController implements ITransferService {

    @Autowired
    private TransferDao transferDao;

    @Autowired
    private IAccountService acctService;

    @ResponseBody
    @PostMapping("/transfer")
    @Transactional
    @Override
    public void transfer(String sourceAcctId, String targetAcctId, double amount) {
        this.acctService.increaseAmount(targetAcctId, amount);
        this.decreaseAmount(sourceAcctId, amount);
    }

    private void decreaseAmount(String acctId, double amount){
        int value = this.transferDao.decreaseAmount(acctId, amount,amount);
        if (value != 1) {
            throw new IllegalStateException("ERROR!");
        }
        System.out.printf("int02 decrease: acct= %s, amount= %7.2f%n", acctId, amount);
    }

}
